package cn.rcth.base.serivce.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.util.*;

import cn.rcth.base.VO.OrderVO;
import cn.rcth.base.constants.BaiseConstants;
import cn.rcth.base.domain.*;
import cn.rcth.base.mapper.*;
import cn.rcth.base.msg.ResultMsg;
import cn.rcth.base.serivce.IOrderSerivce;
import cn.rcth.base.serivce.IPaySerivce;
import cn.rcth.base.util.IdGenerateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class OrderSerivceImpl implements IOrderSerivce {

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderProductMapper orderProductMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeliveryMapper deliveryMapper;


    @Autowired
    private IPaySerivce paySerivce;


    /**
     * 订单
     *
     * @param orderVO 订单的内容
     * @return 生成的订单
     */
    @Override
    public Map orderConfirm(OrderVO orderVO) {
        HashMap<String, Object> map = new HashMap<>();
        //用户
        Long userId = orderVO.getUserId();
        if (userId == null) {
            map.put("code", "请登陆后购买");
            return map;
        } else {
            User user = userMapper.selectByPrimaryKey(userId);
            //商品个数
            Integer productNumber = orderVO.getProductNumber();
            //商品
            Long[] productIds = orderVO.getProductIds();
            for (Long productId : productIds) {
                Product product = productMapper.selectByPrimaryKey(productId);
                if (product.getStorage() < BaiseConstants.DEFAULT_ADDRESS || product.getStorage() < productNumber) {
                    map.put("code", "库存不足");
                    return map;
                }
                map.put("product", product);
            }
            //地址
            Long userAddressId = orderVO.getUserAddressId();
            UserAddress userAddress;
            if (userAddressId == null) {
                //没有输入地址时,显示默认地址
                userAddress = userAddressMapper.selectDefaultUserAddress(userId);

            } else {
                userAddress = userAddressMapper.selectuserAddressById(userAddressId);

            }
            map.put("user", user);
            map.put("userAddress", userAddress);
            map.put("num", orderVO.getProductNumber());
            return map;
        }
    }

    /**
     * 查询用户订单
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public ResultMsg getUserOrder(Long userId, Integer orderStatus) {
        List<Order> orders = orderMapper.getUserOrder(userId, orderStatus);
        return ResultMsg.successResult(orders);
    }

    @Override
    public Order selectOrderById(Long orderId) {
        return orderMapper.selectByPrimaryKey(orderId);
    }

    @Override
    public Order selectOrderBySn(String sn) {
        Order order = orderMapper.selectOrderBySn(sn);
        return order;
    }

    @Override
    public void updateOrder(Order order) {
        orderMapper.updateByPrimaryKey(order);
    }

    @Override//取消订单
    public void cancelOder(Long orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        List<OrderProduct> orderProducts = order.getOrderProducts();
        for (OrderProduct orderProduct : orderProducts) {
            Long productId = orderProduct.getProductId();
            Integer count = orderProduct.getCount();
            Product product = productMapper.selectByPrimaryKey(productId);
            product.setStorage(product.getStorage() + count);
            product.setModifyTime(new Date());
            product.setModifyId(order.getUserId());
            productMapper.updateByPrimaryKey(product);
        }

        order.setStatus(BaiseConstants.ORDER_CANCELLED);
        order.setModifyId(order.getUserId());
        Date date = new Date();
        order.setModifyTime(date);
        order.setCancelTime(date);
        orderMapper.updateByPrimaryKey(order);
    }

    @Override
    public ResultMsg queryOrderDetails(Long orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        Delivery delivery = deliveryMapper.selectDeliveryByOrderId(order.getId());
        Map<String, Object> map = new HashMap<>();
        Date cancelTime = order.getCreateTime();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String format = dateformat.format(cancelTime);

        Date cancelTime1 = order.getCreateTime();
        if (cancelTime1 != null) {
            String cancelTime2 = dateformat.format(cancelTime1);
            map.put("cancelTime2", cancelTime2);
        }

        Date deliveryTime = order.getDeliveryTime();
        if (deliveryTime != null) {
            String deliveryTime1 = dateformat.format(deliveryTime);
            map.put("deliveryTime1", deliveryTime1);
        }
        Date poyTime = order.getPoyTime();
        if (poyTime != null) {
            String poyTime1 = dateformat.format(poyTime);
            map.put("poyTime1", poyTime1);
        }
        try {
            long time = dateformat.parse(format).getTime();
            map.put("time", time);
        } catch (Exception e) {
            e.getMessage();
        }
        map.put("order", order);
        map.put("delivery", delivery);
        return ResultMsg.successResult(map);
    }

    @Override
    public void orderReceipt(Long orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setModifyTime(new Date());
        order.setModifyId(order.getUserId());
        order.setReceiveTime(new Date());
        order.setStatus(BaiseConstants.ORDER_ACCEPTED);
        Delivery delivery = deliveryMapper.selectDeliveryByOrderId(order.getId());
        delivery.setReceiveTime(new Date());
        deliveryMapper.update(delivery);
        orderMapper.updateByPrimaryKey(order);
    }

    @Override
    public ResultMsg orderComeBackOneMore(Long orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        Long addressId = order.getAddressId();
        UserAddress userAddress = userAddressMapper.selectuserAddressById(addressId);
        Map<Object, Object> map = new HashMap<>();
        map.put("order", order);
        map.put("userAddress", userAddress);
        return ResultMsg.successResult(map);
    }

    @Override
    public Map orderStatus(Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        if (userId != null) {
            int unpaid = orderMapper.selectNumByUnpaid(userId);
            int paid = orderMapper.selectNumByPaid(userId);
            int pendingReceipt = orderMapper.selectNumByPendingReceipt(userId);
            map.put("unpaid", unpaid);
            map.put("paid", paid);
            map.put("pendingReceipt", pendingReceipt);
        } else {
            map.put("msg", "当前用户没有授权无法查询数量");
        }

        return map;
    }

    @Override
    public List<Order> selectAll() {
        return null;
    }

    @Override
    public List<Order> selectByText(String text) {
        return null;
    }

    @Override//创建订单
    public ResultMsg orderCreate(OrderVO orderVO, String spbill_create_ip) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        Long userAddressId = orderVO.getUserAddressId();
        //地址
        UserAddress userAddress = userAddressMapper.selectuserAddressById(orderVO.getUserAddressId());
        if (userAddress == null) {
            map.put("code", "您的地址不见了!,请重新选择地址");
            return ResultMsg.successResult(map);
        } else {
            //当前用户
            Long userId = orderVO.getUserId();
            User user = userMapper.selectByPrimaryKey(userId);

            //生成唯一id
            Long nexId = IdGenerateUtil.get().nextId();
            //创建订单
            Order order = new Order();
            order.setOrderSn(nexId);
            order.setUserId(userId);
            order.setText(orderVO.getText());
            order.setAddressId(orderVO.getUserAddressId());
            order.setTotalPrice(orderVO.getProductPrice());
            order.setCreateTime(new Date());
            order.setCreateId(userId);
            order.setStatus(BaiseConstants.ORDER_TO_BE_PAID); //待支付
            orderMapper.insert(order);
            //商品描述
            String body = "";
            //订单商品
            List<OrderProduct> orderProducts = new ArrayList<>();

            //创建订单商品
            Long[] productIds = orderVO.getProductIds();
            for (Long productId : productIds) {

                Product product = productMapper.selectByPrimaryKey(productId);
                //查询库存是否充足
                if (product == null || product.getStorage() < BaiseConstants.DEFAULT_ADDRESS) {
                    return ResultMsg.failedResult("库存不足");
                } else {
                    OrderProduct orderProduct = new OrderProduct();
                    orderProduct.setName(product.getName());
                    orderProduct.setImg(product.getMaxImg());
                    orderProduct.setPrice(product.getPrice());
                    orderProduct.setCount(orderVO.getProductNumber());
                    orderProduct.setOrderId(order.getId());
                    orderProduct.setProductId(product.getId());
                    orderProducts.add(orderProduct);
                    orderProductMapper.insert(orderProduct);
                    String productName = orderProduct.getName();
                    body = body + "-" + productName;

                    //修改商品数量
                    product.setStorage(product.getStorage() - orderVO.getProductNumber());
                    product.setModifyTime(new Date());
                    product.setModifyId(userId);
                    productMapper.updateByPrimaryKey(product);
                }
            }

            String address = userAddress.getAddress();
            String[] split = address.split(" ");
            //创建物流表相关信息
            Delivery delivery = new Delivery();
            delivery.setOrderId(order.getId());
            delivery.setConsignee(userAddress.getConsignee());
            delivery.setConsigneePhone(userAddress.getPhone());
            delivery.setProvince(split[0]);

            delivery.setCity(split[1]);
            delivery.setArea(split[2]);
            delivery.setAddress(userAddress.getDetailedAddress());
            delivery.setStatus(0);
            deliveryMapper.insert(delivery);

            //调用微信支付
            ResultMsg resultMsg = paySerivce.wxPays(body, spbill_create_ip,
                    nexId, orderVO.getProductPrice(), user.getOpenId());
            Map<Object, Object> objectObjectMap = new HashMap<>();
            objectObjectMap.put("resultMsg", resultMsg);
            objectObjectMap.put("orderId", order.getId());
            Date cancelTime = order.getCreateTime();
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = dateformat.format(cancelTime);
            try {
                long time = dateformat.parse(format).getTime();
                objectObjectMap.put("time", time);
            } catch (Exception e) {
                e.getMessage();
            }

            return ResultMsg.successResult(objectObjectMap);
        }
    }
}
